import { AddModulTypeComponent } from './../moduldtype/add-modul-type/add-modul-type.component';
import { MoldService } from './../../../@core/services/mold/mold.service';
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { DeviceToolsService } from 'src/app/@core/services/device-tools/device-tools.service';
import { EditMouldTypeComponent } from '../moduldtype/edit-mould-type/edit-mould-type.component';
@Component({
  selector: 'app-moulds',
  templateUrl: './moulds.component.html',
  styleUrls: ['./moulds.component.scss']
})
export class MouldsComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  model: any =null
  site: any =null
  SearchTerm:string=null;
  pageSizeOptions = [10, 20, 30, 50, 100];
  treeData:any;
  allCheckedStatus = false;
  checkedIds = [];
  deleteIDs = [];
  msgs: Array<Object> = [];
  option:any;//部门option
  pathPids=[]//部门树结构路径
  config = {
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  searchequipmentCategoryValue:any=''
  searcheDepartmentValue:any=''
  filteredTreeNodes:any
  displayTreeData: any[];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '模具编码',
        fieldType: 'text',
        fixedLeft:'200px'
      },
      {
        field: 'name',
        header: '模具名称',
        fieldType: 'text',
        fixedLeft:'300px'

      },
      {
        field: 'workCode',
        header: '型号',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '创建时间',
        fieldType: 'text'
      },
      {
        field: 'workCode',
        header: '备注',
        fieldType: 'text'
      },

    ]
  };//表头数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px'
    },
    {
      field:'name',
      width:'120px'
    },
    {
      field:'name',
      width:'100px'
    },
    {
      field:'name',
      width:'180px'
    },
    {
      field:'name',
      width:'100px'
    },
    {
      field:'name',
      width:'130px'
    },

    {
      field:'name',
      width:'100px'
    },

  ];//表格宽度配置
  tabledata = []
  @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
  @ViewChild(DataTableComponent, { static: true }
    ) datatable!: DataTableComponent;//获取table
  displayTableData: any[];
  Status!: string;
  file: any;
  fixtureTypeId: any=null;
  mouldTypeId: any=null;
  Model: string = null
  selectvalue: string;
  constructor(private dialogService: DialogService,private SharedMethodService:SharedMethodService,private Router:Router,private DeviceToolsService:DeviceToolsService,private MoldService:MoldService){}
  ngOnInit(): void {
    this.MoldService.GetMouldTypesWithChildren(1,999).subscribe((data:any)=>{
      this.treeData=data.items
      this.displayTreeData = [{ mouldTypeName: '全部',mouldTypeId:null}, ...this.treeData];
      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
    })
    this.MoldService.GetMoulds(this.mouldTypeId,this.Status,this.Model,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
  }
  afterTreeInit($event: any){

    if($event['null']){
      $event['null'].data.isActive=true
    }
  }//树形菜单初始化
  getPathPids(node: { mouldTypeId: any; subMouldTypes: any; }, targetId: any, path = []) {
    if (node.mouldTypeId === targetId) {
      return [...path, node.mouldTypeId];
    }
    if (node.subMouldTypes) {
      for (let subNode of node.subMouldTypes) {
        const subPath = this.getPathPids(subNode, targetId, [...path, node.mouldTypeId]);
        if (subPath) {
          return subPath;
        }
      }
    }
    return null;
  } //获取树形菜单pid的路径
  nodeSelected($event:any){
    this.option=$event.data.originItem
    this.mouldTypeId = $event.data.originItem.mouldTypeId;
    this.MoldService.GetMoulds(this.mouldTypeId,this.Status,this.Model,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
    for(let node of  this.treeData){
      const path = this.getPathPids(node, this.mouldTypeId);
      if(path){
        this.pathPids = path;
        break;
      }else{
        this.pathPids = []
      }
    }
  }//树形菜单点击事件
  CreatDepartment(dialogtype?: string){
    let data = {
      options: this.treeData,
      pathPids: this.pathPids && this.pathPids[0] !== null ? this.pathPids : [],
      display: false
    };

    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '新增类别',
      data:data,
      content: AddModulTypeComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.mouldType.mouldTypeName){
              this.MoldService.CreateMouldType(results.modalContentInstance.mouldType).subscribe((data:any)=>{
                this.showToast('success','成功','类别添加成功')
                results.modalInstance.hide();
                this.MoldService.GetMouldTypesWithChildren(1,999).subscribe((data:any)=>{
                  this.treeData=data.items
                  this.displayTreeData = [{ mouldTypeName: '全部',mouldTypeId:null}, ...this.treeData];
                  this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                })
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
            )
            }else{

              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//新建类别
  EditDepartment(dialogtype?: string){
    if(this.mouldTypeId){
      let data = {
        options: this.treeData,
        pathPids: this.pathPids.slice(0, -1),
        display: false,
        option:this.option
      };

      const results = this.dialogService.open({
        id: 'department',
        ...this.config,
        title: '编辑类别',
        data:data,
        content: EditMouldTypeComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {

              if(results.modalContentInstance.mouldType.mouldTypeName){
                this.MoldService.UpdateMouldType(results.modalContentInstance.mouldType,this.mouldTypeId).subscribe((data:any)=>{
                  this.showToast('success','成功','类别编辑成功')
                  results.modalInstance.hide();
                  this.MoldService.GetMouldTypesWithChildren(1,999).subscribe((data:any)=>{
                    this.treeData=data.items
                    this.displayTreeData = [{ mouldTypeName: '全部',mouldTypeId:null}, ...this.treeData];
                    this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                  })
                })
              }
              data.display = true;
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }//编辑类别
  DeleteDepartment(dialogtype?: string){
    if(this.mouldTypeId){
      const results = this.dialogService.open({
        ...this.config,
        title: '删除分类',
        content: '确认删除当前选中的类目？',
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.MoldService.DeleteMouldType(this.mouldTypeId).subscribe((data:any)=>{
                this.showToast('success','成功','删除成功')
                results.modalInstance.hide();
                this.MoldService.GetMouldTypesWithChildren(1,999).subscribe((data:any)=>{
                  this.treeData=data.items
                  this.displayTreeData = [{ mouldTypeName: '全部',mouldTypeId:null}, ...this.treeData];
                  this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
                })
              })
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }

  }//删除类别
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  searchCategory($event:any){
    this.searcheDepartmentValue = $event.target.value;
    if (this.searcheDepartmentValue === '') {
      // 如果用户输入的值为空，显示原先的数据
      this.displayTreeData = this.displayTreeData = [{ fixtureTypeName: '全部',fixtureTypeId:null}, ...this.treeData];

    } else {
      // 否则，显示过滤后的数据
      this.filteredTreeNodes = this.filterCategories(this.treeData, this.searcheDepartmentValue);

      this.displayTreeData = this.filteredTreeNodes;
      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
    }
  }//搜索类目
  pageIndexChange($event: any) {
    this.pager.pageIndex=$event;
    this.MoldService.GetMoulds(this.mouldTypeId,this.Status,this.Model,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
  }//切换页码
  pageSizeChange($event: any){
    this.MoldService.GetMoulds(this.mouldTypeId,this.Status,this.Model,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
  }//改变每页显示数量
  creat(){
    this.Router.navigate(['/pages/mould/add-mould'])
  }//新建设备
  delete(id:any,dialogtype?: string ){
    const results = this.dialogService.open({
      id: 'department',
      data: { id: id },
      ...this.config,
      title: '删除仓库',
      content: '确认删除当前选中的选项？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.MoldService.DeleteMoulds([id]).subscribe((data:any)=>{
              this.showToast('success','成功','删除成功')
              results.modalInstance.hide();
              this.MoldService.GetMoulds(this.mouldTypeId,this.Status,this.Model,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                this.tabledata=data.items;
                this.displayTableData = this.tabledata;
                this.pager.total=data.totalCount;
              })
            },error=>{
              this.showToast('error','失败',error.error)
            }
            )
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        }
      ],
    });
  }//删除
  deltes(dialogtype?: string){
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '删除仓库',
      content: '确认删除当前选中的模具？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.MoldService.DeleteMoulds(this.checkedIds).subscribe((data:any)=>{
              this.showToast('success','成功','删除成功')
              results.modalInstance.hide();
              this.MoldService.GetMoulds(this.mouldTypeId,this.Status,this.Model,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
                this.tabledata=data.items;
                this.displayTableData = this.tabledata;
                this.pager.total=data.totalCount;
              })
            },error=>{
              this.showToast('error','失败',error.error)
            }
            )
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        }
      ],
    });
  }//批量删除
  edit(id:any){
    this.Router.navigate(['/pages/mould/edit-mould'],{queryParams:{id:id}})
  }//编辑
  search(){

    this.MoldService.GetMoulds(this.mouldTypeId,this.Status,this.SearchTerm,this.model,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
  }//搜索
  reset(){
    this.Status = null
    this.mouldTypeId = null
    this.model = ''
    this.SearchTerm = ''
    this.site = ''
    this.MoldService.GetMoulds(this.mouldTypeId,this.Status,this.Model,this.SearchTerm,this.pager.pageIndex,this.pager.pageSize).subscribe((data:any)=>{
      this.tabledata=data.items;
      this.displayTableData = this.tabledata;
      this.pager.total=data.totalCount;
    })
  }//重置
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }){
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem,this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable,'mouldId').subscribe((data:any)=>{
      this.deleteIDs=data;

    })
    this.SharedMethodService.getCheckedRows(this.datatable,'mouldId').subscribe((data:any)=>{
      this.checkedIds=data;
    })
  }//获取选中行
  cleared(){
    this.SharedMethodService.cleared(this.deleteIDs,this.tabledata,this.datatable).subscribe((data:any)=>{
      this.deleteIDs=data;
    })
  }//清空选中行
  setOpenTrue = (node: { open: boolean; subFixtureTypes: any[]; }) => {
    // 为当前节点添加 open: true 属性
    node.open = true;
    // 如果当前节点有子节点，递归处理子节点
    if (Array.isArray(node.subFixtureTypes)) {
      node.subFixtureTypes = node.subFixtureTypes.map(this.setOpenTrue);
    }
    return node;
  }
  filterCategories(categories: any[], keyword: string): any[] {
    const result: any[] = [];
    for (const category of categories) {
      if (category.fixtureTypeName.includes(keyword)) {
        result.push(category);
        continue;
      }
      if (category.subFixtureTypes.length > 0) {
        const filteredSubCategories = this.filterCategories(category.subFixtureTypes, keyword);

        if (filteredSubCategories.length > 0) {
          result.push(...filteredSubCategories);
        }
      }
    }

    return result;
  }

}
